package jmu.cyxwcy.librarymanagement.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.validation.constraints.Pattern;
import jmu.cyxwcy.librarymanagement.mapper.UserMapper;
import jmu.cyxwcy.librarymanagement.pojo.*;
import jmu.cyxwcy.librarymanagement.service.IStudentsService;
import jmu.cyxwcy.librarymanagement.service.UserService;
import jmu.cyxwcy.librarymanagement.service.impl.ClassesServiceImpl;
import jmu.cyxwcy.librarymanagement.utils.JwtUtil;
import jmu.cyxwcy.librarymanagement.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2024-06-25
 */
@RestController
@RequestMapping("/student")
public class StudentsController {
    @Autowired
    private IStudentsService iStudentsService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ClassesServiceImpl classesServiceimpl;

    @PostMapping("/add")
    public Result addUserAndStudent(@RequestBody Students student){
        //查询用户
        Students st = iStudentsService.findByUserName(student.getUsername());
        if(st==null){
            //查询classId
            Classes cls = classesServiceimpl.getClassByName(student.getClassName());
            if (cls == null) {
                return Result.error("班级名无效");
            }
            student.setClassId(cls.getClassId());
            //添加用户
            User user = new User();
            user.setCategoryId(student.getCategoryId());
            userService.getBaseMapper().insert(user);
            student.setUserId(user.getUserId());
            //添加
            String md5String = Md5Util.getMD5String(student.getPassword());
            student.setPassword(md5String);
            iStudentsService.save(student);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{1,16}$") String username, @Pattern(regexp = "^\\S{1,16}$") String password){
        //查询用户
        Students student = iStudentsService.findByUserName(username);
        if(student==null){
            return Result.error("账号错误");
        }
        if(Md5Util.getMD5String(password).equals(student.getPassword())){
            //登录成功生成token
            Map<String,Object> claims=new HashMap<>();
//            claims.put("username",admin.getUserName());
            //获得token令牌
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/findByUserName")
    public Result findByUserName(@RequestParam String username){
        Students student = iStudentsService.findByUserName(username);
        return Result.success(student);
    }

    @GetMapping("/getStudentInfo")
    public Result getStudentInfo(@RequestParam String username){
        MPJLambdaWrapper<Students> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Students.class)
                .select(College::getCollegeName)
                .select(Major::getMajorName)
                .select(Major::getMajorId)
                .select(Classes::getClassName)
                .select(Classes::getClassId)
                .leftJoin(Classes.class, Classes::getClassId, Students::getClassId)
                .leftJoin(Major.class, Major::getMajorId, Classes::getMajorId)
                .leftJoin(College.class, College::getCollegeId, Major::getCollegeId)
                .leftJoin(User.class, User::getUserId, Students::getUserId)
                .eq(!username.isEmpty(), Students::getUsername, username);
        Students student = iStudentsService.joinInfo(queryWrapper);
        return Result.success(student);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Students student) {
        if (student.getPassword() != null) {
            String md5String = Md5Util.getMD5String(student.getPassword());
            student.setPassword(md5String);
        }
        Classes cls = classesServiceimpl.getClassByName(student.getClassName());
        if (cls == null) {
            return Result.error("班级名无效");
        }
        student.setClassId(cls.getClassId());

        User user = userService.getById(student.getUserId());
        if (user != null &&student.getCategoryId()!=null) {
            user.setCategoryId(student.getCategoryId());
            userService.updateById(user);
        }

        iStudentsService.updateById(student);
        return Result.success();
    }

    @DeleteMapping("/delete/{studentId}")
    public Result delete(@PathVariable Integer studentId){
        iStudentsService.removeById(studentId);
        return Result.success();
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestParam Integer studentId,@RequestParam String password,@RequestHeader("Authorization") String token){
        String md5String = Md5Util.getMD5String(password);
        iStudentsService.resetPassword(studentId,md5String);
        //更新密码后删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    @GetMapping("/page")
    public Result<IPage<Students>> findStudentsByPage(@RequestParam Integer pageNum,
                                                      @RequestParam Integer pageSize,
                                                      @RequestParam(defaultValue = "") Integer studentId,
                                                      @RequestParam(defaultValue = "") String studentName,
                                                      @RequestParam(defaultValue = "") String status,
                                                      @RequestParam(defaultValue = "") String collegeName,
                                                      @RequestParam(defaultValue = "") String majorName,
                                                      @RequestParam(defaultValue = "") String className,
                                                      @RequestParam(defaultValue = "") String userId,
                                                      @RequestParam(defaultValue = "") String username,
                                                      @RequestParam(defaultValue = "") String categoryName,
                                                      @RequestParam(defaultValue = "") String categoryId) {
        IPage<Students> page = new Page<>(pageNum, pageSize);
        MPJLambdaWrapper<Students> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Students.class)
                .select(College::getCollegeName)
                .select(Major::getMajorName)
                .select(Major::getMajorId)
                .select(Classes::getClassName)
                .select(Classes::getClassId)
                .select(ReaderCategories::getCategoryName)
                .select(ReaderCategories::getCategoryId)
                .leftJoin(Classes.class, Classes::getClassId, Students::getClassId)
                .leftJoin(Major.class, Major::getMajorId, Classes::getMajorId)
                .leftJoin(College.class, College::getCollegeId, Major::getCollegeId)
                .leftJoin(User.class, User::getUserId, Students::getUserId)
                .leftJoin(ReaderCategories.class, ReaderCategories::getCategoryId, User::getCategoryId)
                .like(studentId!=null, Students::getStudentId, studentId)
                .like(!studentName.isEmpty(), Students::getStudentName, studentName)
                .like(!status.isEmpty(), Students::getStatus, status)
                .like(!userId.isEmpty(), User::getUserId, userId)
                .like(!username.isEmpty(), Students::getUsername,username)
                .like(!categoryName.isEmpty(), ReaderCategories::getCategoryName, categoryName)
                .like(!categoryId.isEmpty(), User::getCategoryId,categoryId)
                .like(!collegeName.isEmpty(), College::getCollegeName, collegeName)
                .like(!majorName.isEmpty(), Major::getMajorName, majorName)
                .like(!className.isEmpty(), Classes::getClassName, className);
        queryWrapper.orderByAsc("student_id");
        IPage<Students> pg = iStudentsService.join(page, queryWrapper);
        return Result.success(pg);
    }

}
